<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>11-添加和删除一行</title>
    <script src="../js/jquery-3.6.0.js"></script>
    <script>
      $(function () {
          init();

          addRow();
      });
      // 初始化方法
      function init() {
        // 准备初始化数据
        let data = [
          {id:"1",name:"小明",sex:"男",sal:"2000"} ,
          {id:"2",name:"小红",sex:"女",sal:"3000"} ,
          {id:"3",name:"小李",sex:"男",sal:"4000"}
        ];

        //准备要插入的字符串
        let str = "";

        // 遍历取数据
        for (let i = 0; i < data.length; i++) {
          let fromDate = data[i];
          str += "<tr align='center'>\n" +
                  "      <td>"+fromDate.id+"</td>\n" +
                  "      <td>"+fromDate.name+"</td>\n" +
                  "      <td>"+fromDate.sex+"</td>\n" +
                  "      <td>"+fromDate.sal+"</td>\n" +
                  "      <td><button onclick='delRow()'>删除</button></td>\n" +
                  "    </tr>"
        }
        console.log(str);

        // 添加到表中
        $("table").append(str);

      }

      // 删除一行数据
      function delRow() {
        let target = event.target;
        $(target).parent().parent().remove();
      }

      // 添加一行数据
      function addRow() {
        $("#doSubmit").click(function () {
          let dataJson = dataToJson();
          let obj = "<tr align='center'>\n" +
                  "      <td>" + dataJson.id + "</td>\n" +
                  "      <td>" + dataJson.name + "</td>\n" +
                  "      <td>" + dataJson.sex + "</td>\n" +
                  "      <td>" + dataJson.sal + "</td>\n" +
                  "      <td><button onclick='delRow()'>删除</button></td>\n" +
                  "    </tr>"
         // $("tr:last").after(obj);
          $("table").append(obj);
        });
      }


      function dataToJson() {
        // 获取添加的数据
        let serializeArray = $("#userAddFrm").serializeArray();
        console.log(serializeArray);
        // 准备数组
        let obj = {};
        $.each(serializeArray,function (index, item) {
          let filedName = item.name;
          let filedValue = item.value;
          obj[filedName] = filedValue;
        });
        console.log(obj);
        return obj;
      }
    </script>

</head>
<body>
  <h1>添加用户</h1>
  <form id="userAddFrm" action="#" method="get">
    ID:<input type="text" name="id">
    NAME:<input type="text" name="name">
    SEX:<input type="radio" name="sex" checked value="男">男 <input type="radio" value="女" name="sex">女
    SAL:<input type="text" name="sal">
    <input type="button" id="doSubmit" value="添加">
    <input type="reset" value="重置">
  </form>
  <hr>
  <h1 align="center">用户列表</h1>
  <table id="userTable" width="100%" border="1" cellspacing="3" cellpadding="3" style="border: 1px solid green">
    <tr>
      <th>ID</th>
      <th>NAME</th>
      <th>SEX</th>
      <th>SAL</th>
      <th>操作</th>
    </tr>
  </table>
</body>
</html>